<template>
  <el-dialog v-loading="loading" :visible.sync="opens" width="60%" append-to-body :before-close="close">
    <el-divider content-position="center">{{ title }}</el-divider>
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="always" class="box-card-left">
          <div class="area">
            <div class="column">
              <p class="zi1">商品名称:</p>
              <p class="zi2">{{ form.goods_name }}</p>
            </div>
            <div class="column column2">
              <p class="zi1">托盘数:</p>
              <p class="zi2">{{ list_num }}</p>
            </div>
            <div class="column">
              <p class="zi1">包装:</p>
              <p class="zi2">{{ form.packing_num }}/{{ form.unit_name }}</p>
            </div>

            <div class="column column2">
              <p class="zi1">剩余数量:</p>
              <p class="zi2">{{ residue }}</p>
            </div>
          </div>
          <el-row>
            <el-col :span="24">
              <el-button type="primary" plain style="float: right;margin-bottom: 20px;" @click="resetting">重置</el-button>
              <el-button
                type="primary"
                plain
                style="float: right;margin-bottom: 20px;margin-right: 25px;"
                @click="addList"
              >增加库位</el-button>
            </el-col>
          </el-row>
          <el-form :inline="true" label-width="60px">
            <div v-for="item in list" :key="item.id">
              <el-row>
                <!--                <el-col :span="3">-->
                <!--                  <el-form-item label="托盘码">-->
                <!--                    <el-input v-model="item.tray_id" />-->
                <!--                  </el-form-item>-->
                <!--                </el-col>-->
                <el-col :span="3">
                  <el-form-item label="数量">
                    <el-input v-model="item.number" type="number" @change="change(item.id, $event)" />
                  </el-form-item>
                </el-col>
                <el-col :span="3">
                  <el-form-item label="箱数">
                    <el-input v-model="item.box_number" />
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <el-form-item label="状态">
                    <el-select v-model="item.goods_status" placeholder="请选择">
                      <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="5" style="position: relative;">
                  <el-form-item label="库位" />
                  <!-- {{ item.config1 }} -->
                  <el-cascader
                    v-model="item.config1"
                    placeholder="请选择"
                    :options="item.configData1"
                    clearable
                    filterable
                    style="width: 100%;position: absolute;bottom: -28%;left: 1%;"
                    :props="Cprops"
                    @change="ck_config(item.id, $event)"
                  />
                  <!-- <el-select v-model="item.config2" placeholder="请选择" style="width: 40%">
                      <el-option
                        v-for="item in item.configData2"
                        :key="item.config_id"
                        :label="item.name"
                        :value="item.config_id"
                      />
                    </el-select> -->
                  <!-- </el-form-item> -->
                </el-col>
<!--                <el-col :span="3">-->
<!--                  <el-form-item label="栈板号">-->
<!--                    <el-input v-model="item.pallet_no" disabled/>-->
<!--                  </el-form-item>-->
<!--                </el-col>-->
                <el-col :span="5" style="margin-left: 10px;">
                  <el-form-item label="SN码">
                    <template>
                      <el-input
                        class="custom-height"
                        rows="2"
                        type="textarea"
                        v-model="item.sn_list"
                      />
                    </template>
                  </el-form-item>
                </el-col>
                <el-col :span="5" style="position: relative;">
                  <el-form-item label="操作" style="position: relative; left: 10%;" />
                  <div style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;position: absolute;top: 8%;left: -20%;">
                    <i class="el-icon-delete" @click="del(item.id)" />
                    <i class="el-icon-document-add" @click="copy(item.id)" />
                  </div>

                </el-col>
              </el-row>

            </div>
          </el-form>
        </el-card>
      </el-col>
      <!--      <el-col :span="13">-->
      <!--        <el-card shadow="always" class="box-card-right" v-loading="loading">-->
      <!--          <el-form ref="form2" label-width="50px">-->
      <!--            <el-form-item label="库位" prop="location">-->
      <!--              <el-cascader-->
      <!--                v-model="location"-->
      <!--                placeholder="请选择库位"-->
      <!--                :options="selectData"-->
      <!--                clearable-->
      <!--                filterable-->
      <!--                :props="props"-->
      <!--                style="width: 30%;"-->
      <!--              />-->
      <!--              <el-input v-model="search" placeholder="请输入库位关键词" style="width: 20%;margin-left: 3%;"></el-input>-->
      <!--              <el-button @click="getBox" icon="el-icon-search" type="primary" plain circle style="margin-left: 15px;"></el-button>-->
      <!--            </el-form-item>-->
      <!--            <el-form-item label="隐藏已占用的库位" label-width="200px">-->
      <!--                <el-checkbox v-model="checked">隐藏</el-checkbox>-->
      <!--            </el-form-item>-->
      <!--            <el-form-item label="" label-width="10px">-->
      <!--              <span v-for="(item,index) in choice" :key="index">{{item}} / </span>-->
      <!--            </el-form-item>-->
      <!--          </el-form>-->
      <!--          <div style="margin-top: 20px;overflow-y:auto;">-->
      <!--            <el-checkbox-group v-model="choice" size="medium" :max="max">-->
      <!--              <el-checkbox-button v-for="item in box" :label="item.name" :key="item.config_id" class="box" border></el-checkbox-button>-->
      <!--            </el-checkbox-group>-->
      <!--          </div>-->
      <!--        </el-card>-->
      <!--      </el-col>-->
    </el-row>
    <el-row style="top: 30px;margin-bottom: 30px;text-align:center;">
      <el-col :span="24">
        <el-button v-if="this.residue == 0" type="primary" size="medium" @click="submit()">提交</el-button>
        <el-button v-if="this.residue !== 0" type="info" size="medium" @click="submit2">提交</el-button>
        <el-button size="medium" @click="close()">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<style>
.custom-height .el-textarea__inner {
  height: 10px; /* 设置你想要的高度 */
}
</style>
<script>
import { att, getSon, createAdd } from '@/api/stock'
import { getConversionList, getSurplus, traySurplus } from '@/api/storehouse'
export default {
  name: 'Seat',
  props: ['opens', 'title', 'form', 'surplus'],
  data() {
    return {
      loading: false,
      u_number: 0,
      list: [], // 托盘数据
      box: [], // 备选的
      selectData: [],
      checked: true,
      choice: [], // 选中的
      search: '',
      location: [],
      sn:'',
      max: 0, // 多选框数量
      total_number: 0, // 总数量
      packing_num: 0, // 包装数量
      props: {
        expandTrigger: 'hover'
        // lazy: true,
        // lazyLoad (node, resolve) {
        // }
      },
      options: [
        {
          value: '1',
          label: 'Good'
        },
        // {
        //   value: '2',
        //   label: 'NG'
        // },
        // {
        //   value: '3',
        //   label: 'Hold'
        // }
      ],
      Cprops: { value: 'config_id', label: 'name', children: 'children' }
    }
  },
  computed: {
    residue() {
      return this.total_number - this.u_number
    },
    list_num() {
      return this.list.length
    }
  },
  watch: {
    list_num() {
      this.max = this.list_num
    },
    form() {
      this.loading = true
      // if (this.form.length == undefined) {
      //   return
      // }
      if (this.form.warehousing_son_id == undefined) {
        return
      }
      traySurplus({ warehousing_son_id: this.form.warehousing_son_id }).then((res) => {
        this.packing_num = res.data.packing_num
        this.total_number = res.data.total_number
      })
      getConversionList({ warehousing_id: this.form.warehousing_id, warehousing_son_id: this.form.warehousing_son_id }).then((res) => {

        this.list = [...res.data.tray_info]
        // console.log(this.list)
        var arr = res.data.warehouse_config_info
        // this.selectList1(arr)
        // for (let i = 0; i < arr.length; i++) {
        //   for (let j = 0; j < arr[i].children.length; j++) {
        //     delete arr[i].children[j].children
        //   }
        // }
        for (let i = 0; i < this.list.length; i++) {
          this.list[i].configData1 = res.data.warehouse_config_info
          this.list[i]._id = this.list[i].id
          this.list[i].id = i
        }
        this.u_number = 0
        for (let i = 0; i < this.list.length; i++) {
          this.u_number += Number(this.list[i].number)
        }
        for (let i = 0; i < this.list.length; i++) {
          this.list[i].config1.push(this.list[i].config2)
        }
        this.selectData = res.data.warehouse_config_info
        // console.log('list', this.list)
        // 复制list 数组 用于重置 叫做list2
        this.list2 = JSON.parse(JSON.stringify(this.list))
        // console.log('list2', this.list2)
        this.loading = false
      })
    }
  },
  created() {
    // this.getLocation()
  },
  methods: {
    submit2() {
      this.$notify.warning('还有剩余商品未分配，请分配完所有商品再进行提交!')
    },
    resetting() {
      this.list = JSON.parse(JSON.stringify(this.list2))
      this.u_number = 0
      for (let i = 0; i < this.list.length; i++) {
        this.u_number += Number(this.list[i].number)
      }
    },
    change(val, event) {
      this.u_number = 0
      for (let i = 0; i < this.list.length; i++) {
        this.u_number += Number(this.list[i].number)
      }
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].id == val) {
          this.list[i].box_number = Math.ceil(Number(event) / Number(this.packing_num))
        }
      }
      if (this.residue < 0) {
        let anum = 0
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].id !== val) {
            anum += Number(this.list[i].number)
          }
        }
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].id == val) {
            this.list[i].number = this.total_number - anum
            this.list[i].box_number = Math.ceil(Number(this.list[i].number) / Number(this.packing_num))
          }
        }
        this.u_number = this.total_number
        console.log(this.u_number, this.total_number)
      }
      // this.u_number = 0
      // this.list.forEach((item) => {
      //   if (item.id == val) {
      //     if (item.number) {
      //       this.u_number += parseInt(item.number)
      //     }
      //   }
      // })
      // this.list.forEach((item) => {
      //   if (item.id == val) {
      //     if (parseInt(event) > parseInt(this.residue)) {
      //       item.number = parseInt(this.residue)
      //       this.u_number += parseInt(this.residue)
      //     } else {
      //       this.u_number += parseInt(event)
      //     }
      //     item.box_number = Math.ceil(parseInt(item.number) / parseInt(this.form.packing_num))
      //   }
      // })
    },
    getBox() {
      if (this.location.length == 0) {
        this.$message({
          showClose: true,
          message: '请选择库位！',
          type: 'error'
        })
        return false
      }
      // this.loading = true
      const location = JSON.parse(JSON.stringify(this.location))
      if (location.length) {
        const that = this
        getSon({config_id: location[1], checked: that.checked, search: that.search}).then(response => {
          if (response.code === 10000) {
            that.box = JSON.parse(JSON.stringify(response.data))
            // that.loading = false
          }
        })
      }
    },
    /** 查询库位 */
    getLocation() {
      const that = this
      att().then(response => {
        if (response.code === 10000) {
          that.selectData = JSON.parse(JSON.stringify(response.data))
          that.selectList(that.selectData)
        }
      })
    },
    /** 处理库位数据 */
    selectList(data) {
      const replaceKey = function (data) {
        data.forEach(function (row, index, arr) {
          const temp = {label: row.name, value: row.config_id}
          if (row.children !== undefined) {
            if (row.children.length > 0) {
              temp['children'] = row.children
            }
            arr[index] = temp
            if (arr[index].children.length > 0) {
              replaceKey(arr[index].children)
            }
          } else {
            arr[index] = temp
          }
        })
      }
      replaceKey(data)
    },
    /** 处理库位数据 */
    selectList1(data) {
      const replaceKey = function (data) {
        data.forEach(function (row, index, arr) {
          const temp = {label: row.name, value: row.config_id}
          if (row.son !== undefined) {
            if (row.son.length > 0) {
              temp['children'] = row.son
            }
            arr[index] = temp
            if (arr[index].children) {
              if (arr[index].children.length > 0) {
                replaceKey(arr[index].children)
              }
            }
          } else {
            arr[index] = temp
          }
        })
      }
      replaceKey(data)
    },
    close() {
      this.u_number = 0
      this.$emit('update:opens', false)
      // console.log(this.list)
    },
    ck_config(val, event) {
      // console.log('val', val, 'event', event)
      return
      const that = this
      that.list.forEach((item, index) => {
        if (item.id == val) {
          getSon({config_id: event[1], checked: false}).then(response => {
            if (response.code === 10000) {
              that.list[index]['configData2'] = JSON.parse(JSON.stringify(response.data))
              // console.log(that.list[index]['configData2'])
            }
          })
        }
      })
      // console.log('that.list', that.list)
    },
    copy(id) {
      const that = this
      var data = {}
      var count = 0
      that.list.forEach((item) => {
        count += item.number ? parseInt(item.number) : 0
        if (item.id == id) {
          var time = new Date().getTime()
          data = JSON.parse(JSON.stringify(item))
          data['id'] = time
        }
      })
      if (parseInt(data.number) > parseInt(that.residue)) {
        this.$message({
          showClose: true,
          message: '超出数量！',
          type: 'error'
        })
      } else {
        if (parseInt(data.number) > 0) {
          this.u_number = count + parseInt(data.number)
        }
        this.list.push(data)
      }
    },
    addList() {
      if (this.residue == 0) {
        this.$message({
          showClose: true,
          message: '没有剩余商品！',
          type: 'error'
        })
      } else {
        var id = new Date().getTime()
        this.list.push({
          id: id,
          tray_id: '',
          number: '',
          box_number: '',
          goods_status:"1",
          config1: "20250708142453",
          status: '',
          configData1: this.selectData,
          config2: '',
          configData2: []
        })
      }
    },
    del(val) {
      // console.log('val', val)
      // console.log('this.list', this.list)
      // return
      this.list = this.list.filter((item) => {
        if (item.id == val) {
          if (item.number) {
            this.u_number = this.u_number - parseInt(item.number)
            // console.log('this.u_number', this.u_number, item.number);
          }
        }
        return item.id != val
      })
    },
    submit() {
      const that = this
      var warehousing = {warehousing_id: that.form.warehousing_id, warehousing_son_id: that.form.warehousing_son_id}
      var goods_info = {goods_id: that.form.goods_id, packing_num: that.form.packing_num}
      var arr = []
      var status = 0 // 1缺数量2缺库位
      console.log(that.list)
      that.list.forEach((item, index) => {
        if (!item.number) {
          status = 1
        }
        if (!item.config1) {
          status = 2
        }
        arr.push({
          id: item._id,
          tray_id: item.tray_id,
          number: item.number,
          status: item.goods_status,
          config_id: item.config1[2],
          box_number: item.box_number,
          sn:item.sn_list,
          pallet_no:item.pallet_no,
        })
      })
      if (that.list_num == 0) {
        return false
      }
      if (that.residue != 0) {
        this.$message({
          showClose: true,
          message: '剩余货物！',
          type: 'error'
        })
      }
      if (status > 0) {
        if (status == 1) {
          this.$message({
            showClose: true,
            message: '空数量！',
            type: 'error'
          })
        } else if (status == 2) {
          this.$message({
            showClose: true,
            message: '空库位！',
            type: 'error'
          })
        }
        return false
      }
      // if (that.residue !== 0) {
      //   this.$message({
      //     showClose: true,
      //     message: '剩余货物！',
      //     type: 'error'
      //   })
      //   return false
      // }
      // for(let i in this.box) {
      //   this.choice.forEach((vo,key)=>{
      //     if(vo == this.box[i].name){
      //       arr[key] = this.box[i].config_id
      //     }
      //   })
      // }
      // this.box.forEach((item,index)=>{
      //   this.choice.forEach((vo,key)=>{
      //     if(vo == item.name){
      //       arr[key] = item.config_id
      //     }
      //   })
      // })
      // if(!this.list.length || !this.choice.length){
      //   this.$message({
      //     showClose: true,
      //     message: '托盘和库位不能为空！',
      //     type: 'error'
      //   })
      //   return false
      // }else if(this.list.length != this.choice.length){
      //   this.$message({
      //     showClose: true,
      //     message: '托盘和库位数量不匹配！',
      //     type: 'error'
      //   })
      //   return false
      // }
      createAdd({list: arr, warehousing: warehousing, goods_info: goods_info}).then(response => {
        if (response.code === 10000) {
          this.$router.push({
            path: '/storehouse/tray',
            query: {
              warehousing_id: this.form.warehousing_id,
              warehousing_son_id: this.form.warehousing_son_id,
              page_date: new Date().getTime()
            }
          })
        }
        this.$emit('update:opens', false)
      })
    }
  }
}
</script>

<style scoped>
.box-card-left {
  height: 600px;
  overflow-y: auto;
}

.box-card-right {
  height: 500px;
  overflow-y: auto;
}

.area {
  float: left;
  width: 100%;
}

.area p {
  font-size: 14px;
  line-height: 24px;
}

.area .column {
  float: left;
  width: 45%;
  margin-right: 10px;
  margin-bottom: 5px;
}

.area .column .img1 {
  float: left;
  width: 200px;
  height: 40px;
  margin-left: 10px;
}

.area .column2 {
  margin-right: 0;
}

.area .zi1 {
  float: left;
  /*border-bottom: 1px solid #fff;*/
  width: 100px;
}

.area .zi2 {
  float: left;
  /*border-bottom: 1px solid #000;*/
  width: 150px;
  margin-left: 10px;
}

i {
  font-size: 25px;
  cursor: pointer;
  margin-top: 25%;
  margin-left: 10%;
}

.box {
  float: left;
  margin: 3px;
  width: 100px;
  display: inline-grid;
}
</style>
